from app.extensions import SessionLocal
from app.models.Student import Student
from app.repositories.StudentRepo import StudentRepository
from app.asserts import Codes
from fastapi import APIRouter, Response, status

class StudentService:
    def __init__(self, db: SessionLocal):
        self.repo = StudentRepository(db)

    def add_student(self,student_name,student_gender,student_clas_id):
        cals = self.repo.get_clas_by_id(student_clas_id)
        if cals is None:
            return {"code": status.HTTP_404_NOT_FOUND, "data": None, "message": "班级不存在"}
        try:
            # 创建学生对象
            student = Student(
                name=student_name,
                gender=student_gender,
                clas_id=student_clas_id
            )

            # 调用Repo层保存学生
            result = self.repo.add_student(student)

            if result:
                return {"code": status.HTTP_200_OK, "data": None, "message": "学生已创建成功"}
            else:
                return {"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "data": None, "message": "学生创建失败"}

        except Exception as e:
            print(f"添加学生失败: {str(e)}")
            return {"code": Codes.SERVICE_ERROR, "data": None, "message": "学生创建失败"}

    def get_by_keyword(self, keyword):
        """
        根据关键字查询数据
        :param keyword: 关键字
        :return:
        """
        data = self.repo.get_by_keyword(keyword)
        return {"code": status.HTTP_200_OK, "data": data, "message": "查询成功"}

    def modify_student(self,id, name, gender,clas_id):
        success = self.repo.modify_student(id, name, gender, clas_id)
        if success:
            return {"code": status.HTTP_200_OK, "data": True, "message": "修改成功"}
        else:
            return {"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "data": False, "message": "修改失败"}

    def delete_student(self, id):
        if not self.repo.get_student_by_id(id):
            return {"code": status.HTTP_404_NOT_FOUND, "data": None, "message": "学生不存在"}

        success = self.repo.delete_student(id)
        if success:
            return {"code": status.HTTP_200_OK, "data": None, "message": "删除成功"}
        else:
            return {"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "data": None, "message": "删除失败"}